package com.example.Controller;

import com.example.Service.CateGoryService;
import com.example.Service.UserService;
import com.example.pojo.CateCory;
import com.example.pojo.Result;
import com.example.pojo.User;
import com.example.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 文章分类接口(完结)
 */
@RequestMapping("/category")
@RestController
@Slf4j
public class CateGoryController {

    //文章分类
    @Autowired
    private CateGoryService cateGoryService;

    //用户
    @Autowired
    private UserService userService;

    //1.新增文章分类
    @PostMapping
    public Result addCateGory(@RequestBody @Validated CateCory cateCory, @RequestHeader(name = "token") String token){

        Claims claims = JwtUtils.parseJWT(token);
        String phone = (String) claims.get("phone");

        User e = userService.selectUser(phone,null);
        //1.查询改用户并且获取创建者id,通过该id添加分类文章
        int createId = e.getId();

        /**2.查询该用户文章，如果添加重名，返回错误信息
         * 防止同一个用户中有相同的文章类型
         */
        List<CateCory> c = cateGoryService.selectCateGoryByUserid(createId);
        for (CateCory cory : c) {
            if(cory.getName().equals(cateCory.getName())){
                return Result.error("该分类存在，请重新添加");
            }

        }

        //3.直接添加
        cateGoryService.addcateGory(cateCory,createId);

        return Result.success();
    }

    //2.展示当前用户id文章分类列表
    @GetMapping
    public Result listCateCory(@RequestHeader(name = "token") String token){
        Claims claims = JwtUtils.parseJWT(token);
        String phone = (String) claims.get("phone");
        User e = userService.selectUser(phone,null);
        int createId = e.getId();

        List<CateCory> data = cateGoryService.list(createId);


        return Result.success(data);
    }

    //3.根据当前文章id删除文章
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id){
        cateGoryService.delete(id);
        return Result.success();
    }


    /**4.根据文章id 查看文章详情
     * 5.修改文章*/
    @GetMapping("/detail")//简单参数的传递
    public Result selectCateCory(Integer id){
        CateCory c = cateGoryService.selectDetail(id);

        return Result.success(c);
    }

    //修改文章数据
    @PutMapping
    public Result updataCateCory(@RequestBody @Validated CateCory cateCory){

        log.info("传来的数据{}",cateCory);
        cateGoryService.updata(cateCory);
        return Result.success();
    }






}
